<script setup>
import { ref, computed } from 'vue'
import { useRouter } from 'vue-router'
import { UserOutlined, LockOutlined } from '@ant-design/icons-vue'
import { message } from 'ant-design-vue'
import request from '@/utils/request'

const router = useRouter()
const formState = ref({
  username: '',
  password: '',
  confirmPassword: '',
})

const rules = {
  username: [
    { required: true, message: '请输入用户名', trigger: 'blur' },
    { min: 3, max: 12, message: '用户名长度应为3-12个字符', trigger: 'blur' },
  ],
  password: [
    { required: true, message: '请输入密码', trigger: 'blur' },
    { min: 6, message: '密码至少6个字符', trigger: 'blur' },
  ],
  confirmPassword: [
    { required: true, message: '请确认密码', trigger: 'blur' },
    ({ getFieldValue }) => ({
      validator(_, value) {
        if (!value || getFieldValue('password') === value) {
          return Promise.resolve()
        }
        return Promise.reject(new Error('两次输入的密码不一致'))
      },
    }),
  ],
}

const loading = ref(false)

const onFinish = async() => {
  loading.value = true
  //请求后端完成注册
  const res = await request.post('/user/register', formState.value)
  if(res.data.code === 200){
    setTimeout(() => {
    loading.value = false
    message.success('注册成功，请登录')
    router.push('/login')
  }, 1000)
  }else{
    loading.value = false
    message.error('注册失败',res.message)
  }
  
}

const isLoggedIn = computed(() => {
  return localStorage.getItem('user') !== null
})
</script>

<template>
  <div class="register-container">
    <h2>用户注册</h2>
    <a-form
      :model="formState"
      name="register"
      :rules="rules"
      @finish="onFinish"
      autocomplete="off"
    >
      <a-form-item name="username">
        <a-input v-model:value="formState.username" placeholder="用户名">
          <template #prefix>
            <UserOutlined />
          </template>
        </a-input>
      </a-form-item>

      <a-form-item name="password">
        <a-input-password v-model:value="formState.password" placeholder="密码">
          <template #prefix>
            <LockOutlined />
          </template>
        </a-input-password>
      </a-form-item>

      <a-form-item name="confirmPassword">
        <a-input-password v-model:value="formState.confirmPassword" placeholder="确认密码">
          <template #prefix>
            <LockOutlined />
          </template>
        </a-input-password>
      </a-form-item>

      <a-form-item>
        <a-button 
          type="primary" 
          html-type="submit" 
          :loading="loading" 
          block
        >
          注册
        </a-button>
      </a-form-item>
      
      <a-form-item>
        <div class="form-footer">
          已有账号？
          <router-link to="/login">立即登录</router-link>
        </div>
      </a-form-item>
    </a-form>
  </div>
</template>

<style scoped>
.register-container {
  max-width: 400px;
  margin: 0 auto;
  padding: 20px;
}
h2 {
  text-align: center;
  margin-bottom: 30px;
}
.form-footer {
  text-align: center;
}
</style>